<?php
/**
 * Created by PhpStorm.
 * User: dengqihua
 * Date: 2017/5/29
 * Time: 上午9:27
 */
namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function loginlogs()
    {
        return $this->hasMany('App\Model\UserLoginLog');
    }

    /**
     * 根据账号（用户名，手机，邮箱）获取用户信息
     * @param $account
     * @return mixed
     */
    public function getUserInfoByAccount($account)
    {
        $condition = [];
        switch ($account) {
            case check_username($account):
                $condition['name'] = $account;
                break;
            case check_email($account):
                $condition['email'] = $account;
                break;
            case check_mobile($account):
                $condition['mobile'] = $account;
                break;
            default:
                $condition['name'] = $account;
        }
        $info = $this->where($condition)->first();
        return $info;
    }

    /**
     * 验证账号密码是否匹配；账号包含用户名，手机，邮箱
     * @param $account
     * @param $password
     * @return bool
     */
    public function vaildAccountPassword($account, $password)
    {
        if (!$account || !$password) {
            return FALSE;
        }
        $condition = [];
        switch ($account) {
            case check_username($account):
                $condition['name'] = $account;
                break;
            case check_email($account):
                $condition['email'] = $account;
                break;
            case check_mobile($account):
                $condition['mobile'] = $account;
                break;
            default:
                $condition['name'] = $account;
        }

        $password_hash = $this->where($condition)->value('password');
        if (password_verify($password, $password_hash)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 检查邮箱是否存在
     * @param $email
     * @return bool
     */
    public function vaildEmailExists($email)
    {
        if (!$email || !check_email($email)) {
            return FALSE;
        }
        if ($this->where('email', $email)->count()) {
            return true;
        } else {
            return false;
        }
    }

}
